const express = require('express')
const Router = express.Router()

const model = require('../model/model')

const User = model.getModel('user')

Router.post('/save', (req, res) => {
    console.log(req.body)
    const { name, phone } = req.body
    let isSend = false
    let qrcode = ''
    const UserData = new User({ name, phone, isSend, qrcode })
    User.find({
        phone
    }, (err, dd) => {
        if (err) {
            return res.json({ code: 1, msg: '服务出错了！！！' })
        }
        if (dd.length !== 0) {
            return res.json({ code: 1, msg: `手机号: ${phone} 重复了` })
        }
        UserData.save((e, d) => {
            if (e) {
                return res.json({ code: 1, msg: '服务出错了！！！' })
            }
            return res.json({ code: 200, data: '添加成功' })
        })
    })

})

Router.post('/sendMsg', (req, res) => {
    User.find({
        phone
    }, (err, dd) => {
        if (dd.length !== 0) {


            return res.json({ code: 1, msg: `手机号: ${phone} 重复了` })
        }
    })

    return res.json({ code: 200, data: '发送短信成功' })
})

Router.get('/one', (req, res) => {
    let { phone } = req.query
    User.findOne({
        phone
    }, (e, d) => {
        if (e) {
            return res.json({ code: 1, msg: '服务出错了！！！' })
        }
        console.log(d)
        if (d) {
            return res.json({ code: 200, data: d })
        } else {
            return res.json({ code: 200, data: '没有该用户' })
        }

    })
})


Router.post('/list', (req, res) => {
    var count = 0;
    let { page, rows, name, phone } = req.body
    var query = User.find({});
    query.skip((page - 1) * rows);
    query.limit(rows);
    if (name) {
        query.where('name', name);
    }
    if (phone) {
        query.where('phone', phone);
    }
    //计算分页数据
    console.log('111111111')
    User.find(function(err, rs) {
        console.log(rs)
        if (err) {
            res.send(err);
        } else {
            //计算数据总数
            // user.find(function(err, result) {
            //     jsonArray = { rows: rs, total: result.length };
            //     return res.json({ code: 200, data: jsonArray });
            // });

            query.exec(function(err, result) {
                jsonArray = { total: rs.length, data: result, code: 200, };
                return res.json(jsonArray);
            });
        }
    });
})

Router.get('/test', (req, res) => {
    console.log(req.query.name)
    return res.json({ code: 200, data: '成功了: ' + req.query.name })
})

Router.get('/getone', (req, res) => {
    console.log(req.query.name)
    Base.find({}, (e, d) => {
        return res.json({ code: 200, data: d })

    })
})

module.exports = Router